import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'
import { JSEncrypt } from 'jsencrypt'
//用户的id和登录凭证用来修改用户性别
interface GetUserInfoState {
  userId: string
  sessionId: string
}

interface RegistRawState {
  email: string
  code: string
  pwd1: string
  pwd2: string
  invitationCode?: string
}

export const useUserStore = defineStore('user', () => {
  const publicKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`

  //加密
  const encryptedData = (publicKey: string, data: string) => {
    // 新建JSEncrypt对象
    const encryptor = new JSEncrypt()
    // 设置公钥
    encryptor.setPublicKey(publicKey) // publicKey为公钥
    // 加密数据
    return encryptor.encrypt(data) //data就是需要加密的密码
  }
  // 存储当前用户密码，初始值可从登录等情况获取，这里先空着示例
  const storedPassword = ref('')
  // 存储用户ID，初始值为空字符串
  const storedUserId = ref('')
  // 存储会话ID，初始值为空字符串
  const storedSessionId = ref('')

  // 设置密码的方法，用于模拟从登录等情况设置密码到Pinia中存储
  const setPassword = (password: string) => {
    storedPassword.value = password
  }

  // 设置用户ID的方法
  const setUserId = (userId: string) => {
    storedUserId.value = userId
  }

  // 设置会话ID的方法
  const setSessionId = (sessionId: string) => {
    storedSessionId.value = sessionId
  }

  // 获取密码的方法，用于后续验证登录时输入的密码是否正确
  const getPassword = () => {
    return storedPassword.value
  }

  // 获取用户ID的方法
  const getUserId = () => {
    return storedUserId.value
  }

  // 获取会话ID的方法
  const getSessionId = () => {
    return storedSessionId.value
  }

  // 登陆
  const login = async (data: any) => {
    const inputPassword = data.pwd
    const storedPwd = getPassword()
    console.log(getPassword())
    console.log(storedPwd)
    console.log(data, '111')
    //这几个都没有获取到
    // if (inputPassword!== storedPwd) {
    //     console.log({ type: 'danger', message: '登录密码与保存的密码不一致，请检查输入！' });
    //     return;
    // }
    data.pwd = encryptedData(publicKey, data.pwd) as string
    const resp = await axios.post('health/user/v1/login', data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    })
    if (resp.status === 200) {
      const passwordFromServer = 'passwordFromServerValue'
      const userIdFromServer = resp.data.userId
      const sessionIdFromServer = resp.data.sessionId
      setPassword(passwordFromServer)
      setUserId(userIdFromServer)
      setSessionId(sessionIdFromServer)
      console.log({ type: 'primary', message: '登录成功' })
    } else {
      console.log({ type: 'danger', message: '登录失败' })
    }
  }

  const userInfor = ref({
    // 年龄
    age: -1,
    // 邮箱
    email: '',
    // 头部图片
    headPic: '',
    // 身高
    height: -1,
    // 用户id
    userId: -1,
    // 邀请码
    invitationCode: '-1',
    // 激光码
    jiGuangPwd: '',
    // 昵称
    nickName: '',
    // 会话id
    sessionId: '',
    // 性别
    sex: -1,
    // 用户名
    userName: '',
    // 体重
    weight: -1,
    // 不清楚
    whetherBingWeChat: -1,
    // 不清楚
    faceFlag: -1,
  })

  //注册
  const regist = async (data: RegistRawState) => {
    // 密码加密 rsa
    data.pwd1 = encryptedData(publicKey, data.pwd1) as string
    data.pwd2 = data.pwd1
    // 请求
    const resp = await axios.post('health/user/v1/register', data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    })

    console.log(resp)
  }

  //获取用户信息
  const getuserInfor = async (userObj: GetUserInfoState) => {
    const resp = await axios.get('/health/user/verify/v1/getUserInfoById', { params: userObj })
    console.log(resp)
  }

  return {
    getuserInfor,
    userInfor,
    regist,
    login,
    setPassword,
    getPassword,
    setUserId,
    getUserId,
    setSessionId,
    getSessionId,
  }
})

interface User {
  sex: string
  signsData: {
    height: number
    weight: number
    age: number
  }
}

export const userStore = defineStore('main', {
  state: (): User => ({
    sex: '',
    signsData: {
      height: 0,
      weight: 0,
      age: 0,
    },
  }),
  actions: {
    setSex(sex: string) {
      this.sex = sex
    },
    setSignsData(signsData: User['signsData']) {
      this.signsData = signsData
    },
  },
})
